package com.unhz.taigu.interface_controllers.deliveryOrder;

import com.unhz.generator.enums.EnumValid;
import com.unhz.generator.pojo.*;
import com.unhz.generator.utils.EmptyUtil;
import com.unhz.generator.utils.JsonResult;
import com.unhz.taigu.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Author: 沈佳庆
 * @Description: 交货订单
 * @Date: Created in 下午 4:38 2018/3/3 0003
 * @Modified By: V1.0.0
 */
@RestController
@RequestMapping("/IDeliveryOrder")
public class IDeliveryOrderController {

    @Autowired
    private DeliveryInfoService deliveryInfoService;

    @Autowired
    private DeliveryOrderService deliveryOrderService;

    @Autowired
    private ProductionOrderInfoService productionOrderInfoService;

    @Autowired
    private ProductionOrderService productionOrderService;

    @Autowired
    private OrderService orderService;

    @Autowired
    private ReceivingInfoService receivingInfoService;

    @Autowired
    private UserService userService;

    /**
     * 删除收货订单
     * @param deliveryId
     * @return
     */
    @RequestMapping("/deleteDeliveryOrder")
    @ResponseBody
    public JsonResult deleteDeliveryOrder(@RequestParam(value = "deliveryId",required = false) Integer deliveryId){
        System.out.println("------------------------------"+deliveryId);
        int count = deliveryOrderService.deleteDeliveryOrder(Long.valueOf(deliveryId));
//        deliveryInfoService.deleteDeliveryOrderInfo(Long.valueOf(deliveryId));
        if(EmptyUtil.isEmpty(count)){
            return JsonResult.failure("删除交货订单失败!");
        }
        return JsonResult.success("删除交货订单成功!");

    }

    /**
     * 新增交货订单前查询交货订单剩余数量
     * @param model
     * @param productionId 排产订单id
     * @return
     */
    @RequestMapping("/selectByInsert")
    public JsonResult selectByInsert(Model model,
                                     @RequestParam(value= "productionId",required = false) Integer productionId){
        //根据排产订单id查询合同中的尺码和数量
        List<ProductionOrderInfo> productionOrderInfoList =  productionOrderInfoService.selectByOrderId(Long.valueOf(productionId));
        //根据排产订单id查询交货订单中的数量
        List<DeliveryOrder> deliveryOrderList =  deliveryOrderService.selectDeliveryOrder(Long.valueOf(productionId));

        model.addAttribute("deliveryOrderList",deliveryOrderList);
        int [] number = new int[productionOrderInfoList.size()];
        for(int i=0;i<deliveryOrderList.size();i++){
            Long deliveryId = deliveryOrderList.get(i).getId();
            List<DeliveryInfo> deliveryInfoList = deliveryInfoService.selectByDeliveryOrderId(deliveryId);
            int nums;
            for(int j=0;j<deliveryInfoList.size();j++){
                nums = deliveryInfoList.get(j).getNumber();
                number[j] += nums;
            }
        }
        int count;
        List list=new ArrayList();
        int [] counts = new int[productionOrderInfoList.size()];
        for(int x=0;x<number.length;x++){
            count = productionOrderInfoList.get(x).getNumber() - number[x];
            list.add(count);
            counts[x] = count;
        }
        //查询用户的收货信息
        //根据排产订单id查询用户id
        ProductionOrder productionOrder = productionOrderService.selectById(productionId);
        Integer orderId = productionOrder.getOrderId();
        Order order = orderService.selectOrderById(orderId);
        Integer userId = order.getUserId();
        ReceivingInfo receivingInfo = receivingInfoService.selectReceivingInfo(userId);
        //收货地址
        model.addAttribute("receivingInfo",receivingInfo);
        if(EmptyUtil.isEmpty(receivingInfo)){
            User user = userService.selectById(userId);
            model.addAttribute("user",user);
        }else{
            model.addAttribute("receivingInfo",receivingInfo);
        }

        model.addAttribute("list",list);
        return JsonResult.success("查询交货订单剩余数量成功",model );
    }

    /**
     * 修改交货订单前查询交货订单剩余数量
     * @param model
     * @param deliveryId 交货订单id
     * @return
     */
    @RequestMapping("/selectByUpdate")
    public JsonResult selectByUpdate(Model model,
                                     @RequestParam(value= "deliveryId",required = false) Integer deliveryId){
        DeliveryOrder deliveryOrder = deliveryOrderService.findDeliveryOrder(Long.valueOf(deliveryId));
        if(EmptyUtil.isEmpty(deliveryOrder)){
            return JsonResult.failure("查询无交货订单信息!");
        }
        Integer productionId = deliveryOrder.getProductionId();
        //根据排产订单id查询排产订单信息中的尺码和数量
        List<ProductionOrderInfo> productionOrderInfo = productionOrderInfoService.selectByOrderId(Long.valueOf(productionId));
        //根据排产订单id查询交货订单中的数量
        List<DeliveryOrder> deliveryOrderList = deliveryOrderService.selectDeliveryOrder(Long.valueOf(productionId));

        for (DeliveryOrder d:deliveryOrderList) {
            model.addAttribute("deliveryOrderList", d);
        }

        for(int i=0;i<deliveryOrderList.size();i++) {

            Long deliveryIds = deliveryOrderList.get(i).getId();
            if (deliveryIds == Long.valueOf(deliveryId)) {
                continue;
            }
            List<DeliveryInfo> deliveryInfoList = deliveryInfoService.selectByDeliveryOrderId(deliveryIds);
            int [] number = new int[productionOrderInfo.size()];
            for(int j=0;j<productionOrderInfo.size();j++){
                number[j] +=  productionOrderInfo.get(j).getNumber();
            }
            //交货订单信息数量
            int[] counts = new int[deliveryInfoList.size()];
            for (int x = 0; x < number.length; x++) {
                counts[x] =number[x]- deliveryInfoList.get(x).getNumber();
            }
            model.addAttribute("counts",counts);
        }
        return JsonResult.success("查询交货订单信息!",model);
    }

    /**
     * 修改交货订单信息
     * @param deliveryOrder
     * @param size
     * @param number
     * @return
     */
    @RequestMapping("/updateDeliveryOrder")
    public JsonResult updateDeliveryOrder(DeliveryOrder deliveryOrder,
                                          @RequestParam(value = "size",required = false) String[] size,
                                          @RequestParam(value = "number",required = false) Integer[] number){
        int count = deliveryOrderService.updateDeliveryOrder(deliveryOrder);
        Long deliveryId = deliveryOrder.getId();
        if(EmptyUtil.isEmpty(count)){
            return JsonResult.failure("修改交货订单失败!");
        }
        DeliveryInfo deliveryInfo = null;
        for(int i=0;i<size.length;i++){
            deliveryInfo = new DeliveryInfo();
            deliveryInfo.setDeliveryId(deliveryId);
            deliveryInfo.setSize(size[i]);
            deliveryInfo.setNumber(number[i]);
            deliveryInfo.setValid((byte) EnumValid.ENABLED.getIndex());
            deliveryInfoService.updateDeliveryOrderInfo(deliveryInfo);
        }
        return JsonResult.success("修改交货订单成功!");
    }

    /**
     * 修改收货信息
     * @param deliveryOrder 收货订单

     * @return
     */
    @RequestMapping("/updateAddress")
    @ResponseBody
    public JsonResult updateAddress(DeliveryOrder deliveryOrder,
                                    @RequestParam(value= "userid",required = false) Integer userid,
                                    @RequestParam(value= "adminName",required = false) String adminName
    ){
      /*  //根据收货订单id查询用户id
        DeliveryOrder deliveryOrders = deliveryOrderService.findDeliveryOrder(Long.valueOf(deliveryId));
        *//**排产订单id**//*
        Integer productionId = deliveryOrders.getProductionId();
        *//*排产订单*//*
        System.err.println("-------------  *//*排产订单*//*--------"+productionId);
        ProductionOrder productionOrder = productionOrderService.selectById(productionId);
        *//** 订单Id *//*
        Integer orderId = productionOrder.getOrderId();
        *//*订单表*//*
        System.err.println("-------------*订单表--------"+orderId);
        Order order = orderService.selectOrderById(orderId);
        *//**用户id**//*
        Integer userId = order.getUserId();*/
        System.err.println("-------------* /**用户id**/--------"+userid);
        //根据用户id查询用户收货信息
        List<ReceivingInfo> receivingInfoList = receivingInfoService.selectAllReceivingInfo(userid);
        ReceivingInfo receivingInfos = new ReceivingInfo();
        System.out.println(receivingInfoList.size());
        for(ReceivingInfo receivingInfo:receivingInfoList){
            System.err.println("-------------* /**用户id**/--------"+receivingInfo.getUpdateBy()+"----**---------"+adminName);
            if(receivingInfo.getUserName().equals(deliveryOrder.getUserName())
                    && receivingInfo.getUserPhone().equals(deliveryOrder.getUserPhone())
                    && receivingInfo.getProvince().equals(deliveryOrder.getProvince())
                    && receivingInfo.getCity().equals(deliveryOrder.getCity())
                    && receivingInfo.getCounties().equals(deliveryOrder.getCounties())
                    && receivingInfo.getAddress().equals(deliveryOrder.getWarehouseAddress())
                    ) {
                Integer receivingId = receivingInfo.getId();
                System.err.println("-------------修改id--------" + receivingId);
                receivingInfos.setProvince(deliveryOrder.getProvince());
                receivingInfos.setCity(deliveryOrder.getCity());
                receivingInfos.setCounties(deliveryOrder.getCounties());
                receivingInfos.setAddress(deliveryOrder.getWarehouseAddress());
                receivingInfos.setUserName(deliveryOrder.getUserName());
                receivingInfos.setUserPhone(deliveryOrder.getUserPhone());
                receivingInfos.setUpdateBy(adminName);
                receivingInfos.setId(receivingId);
                receivingInfos.setUpdateTime(new Date());
                int count = receivingInfoService.updateReceivingInfoid(receivingInfos);
                if (count > 0) {
                    return JsonResult.success("修改收货信息成功!", 1);
                }
            }

          }
            receivingInfos.setProvince(deliveryOrder.getProvince());
            receivingInfos.setCity(deliveryOrder.getCity());
            receivingInfos.setCounties(deliveryOrder.getCounties());
            receivingInfos.setAddress(deliveryOrder.getWarehouseAddress());
            receivingInfos.setCreateTime(new Date());
            receivingInfos.setCreateBy(deliveryOrder.getUserName());
            receivingInfos.setUserName(deliveryOrder.getUserName());
            receivingInfos.setUserPhone(deliveryOrder.getUserPhone());
            receivingInfos.setUpdateBy(adminName);
            receivingInfos.setUpdateTime(new Date());
            receivingInfos.setUserId(userid);
            receivingInfos.setValid(1);
            receivingInfoService.insertAddress(receivingInfos);
            return JsonResult.success("新增成功!",1);
    }


    /**
     * 新增交货订单
     * @param deliveryOrder
     * @param number 交货订单数量
     * @param size 交货订单尺码
     * @return
     */
    @RequestMapping("/insert")
    public JsonResult insert(DeliveryOrder deliveryOrder,
                              @RequestParam(value= "number",required = false) Integer[] number,
                              @RequestParam(value= "size",required = false) String[] size,
                             @RequestParam(value= "time",required = false) String time) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date planDate = sdf.parse(time);

        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        String planDat = dateFormat.format(new Date());
        deliveryOrder.setDeliveryNo(planDat+deliveryOrder.getWaybillNo()+deliveryOrder.getSizeType());
        deliveryOrder.setDeliveryTime(planDate);
        deliveryOrder.setStatus(Byte.valueOf("1"));
        deliveryOrder.setValid(Byte.valueOf("1"));
        deliveryOrder.setApplyTime(new Date());
        int count = deliveryOrderService.insertDeliveryOrder(deliveryOrder);
        if(count<1){
            return JsonResult.failure("新增交货订单失败!");
        }
        Long deliveryId = deliveryOrder.getId();
        DeliveryInfo deliveryInfo = null;
        for(int i=0;i<size.length;i++){
            deliveryInfo = new DeliveryInfo();
            deliveryInfo.setDeliveryId(deliveryId);
            deliveryInfo.setSize(size[i]+"#");
            deliveryInfo.setNumber(number[i]);
            deliveryInfo.setValid((byte) EnumValid.ENABLED.getIndex());
            deliveryInfoService.addDeliveryInfo(deliveryInfo);
        }
        return JsonResult.success("新增交货订单成功!");
    }

}
